package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.mapper.UnitMapper;
import com.yupi.springbootinit.model.dto.unit.UnitAddRequest;
import com.yupi.springbootinit.model.dto.unit.UnitQueryRequest;
import com.yupi.springbootinit.model.dto.unit.UnitUpdateRequest;
import com.yupi.springbootinit.model.entity.Unit;
import com.yupi.springbootinit.service.UnitService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;

/**
* @author zlc
* @description 针对表【unit(单位信息表)】的数据库操作Service实现
* @createDate 2024-07-23 16:17:31
*/
@Service
public class UnitServiceImpl extends ServiceImpl<UnitMapper, Unit>
    implements UnitService{

    @Override
    public long addUnit(UnitAddRequest unitAddRequest) {
        Unit unit = new Unit();
        BeanUtils.copyProperties(unitAddRequest, unit);
        this.save(unit);
        return unit.getId();
    }

    @Override
    public boolean deleteUnit(DeleteRequest deleteRequest) {
        long id = deleteRequest.getId();
        return this.removeById(id);
    }

    @Override
    public boolean updateUnit(UnitUpdateRequest unitUpdateRequest) {
        Unit unit = new Unit();
        BeanUtils.copyProperties(unitUpdateRequest, unit);
        return this.updateById(unit);
    }

    @Override
    public Unit getUnitById(long id) {
        return this.getById(id);
    }

    @Override
    public List<Unit> listUnit(UnitQueryRequest unitQueryRequest) {
        QueryWrapper<Unit> queryWrapper = getQueryWrapper(unitQueryRequest);
        return this.list(queryWrapper);
    }

    @Override
    public Page<Unit> listUnitByPage(UnitQueryRequest unitQueryRequest) {
        long current = unitQueryRequest.getCurrent();
        long size = unitQueryRequest.getPageSize();
        Page<Unit> page = new Page<>(current, size);
        QueryWrapper<Unit> queryWrapper = getQueryWrapper(unitQueryRequest);
        return this.page(page, queryWrapper);
    }

    private QueryWrapper<Unit> getQueryWrapper(UnitQueryRequest unitQueryRequest) {
        QueryWrapper<Unit> queryWrapper = new QueryWrapper<>();
        if (unitQueryRequest == null) {
            return queryWrapper;
        }
        Long id = unitQueryRequest .getId();
        if (id != null && id > 0) {
            queryWrapper.eq("id", id);
        }
        return queryWrapper;
    }
}